import Ranking from "./tops/Ranking.js";
import fetch from "node-fetch";
import _ from "lodash";
import { Serv } from "#fansky.models";
import { Data, Render } from "#fansky";
import { getData, checkData } from "./tops/UserLocalData.js";

export class Tops extends plugin {
    constructor() {
        super({
            name: '宝箱、成就排行',
            dsc: '宝箱、成就排行',
            event: 'message',
            priority: 3000,
            rule: [
                {
                    reg: /^#(宝箱|成就)(排[行名]榜?)(.*)$/,
                    fnc: 'rank'
                }
            ]
        })
    }

    async rank(e) {
        let msg = e.original_msg || e.msg
        if (!msg) {
            return false
        }
        if (/宝箱/.test(msg)) {
            e.box = true
        }
        return e.isGroup && msg.includes('榜') ? await this.groupRanking(e) : await this.Ranking(e);
    }

    async Ranking(e) {
        let uid = await Serv.getUid(e)
        if (!uid) {
            return e.reply('请先绑定uid, 或在指令后面加你要查询的uid')
        }

        // 国际服读取本地数据
        if (/([6-9]|18)[0-9]{8}/.test(uid)) {
            e.reply('『国际服』: 获取本地数据....')
            return await getData(e, uid)
        }

        let url;
        if (e.box) {
            url = `https://feixiaoqiu.com/search_box_ajax/?draw=1&columns[0][data]=total_index_div()&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=false&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=nick_name_div()&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=false&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=title_div()&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=false&columns[2][search][value]=&columns[2][search][regex]=false&columns[3][data]=grade_div()&columns[3][name]=&columns[3][searchable]=true&columns[3][orderable]=false&columns[3][search][value]=&columns[3][search][regex]=false&columns[4][data]=box_div()&columns[4][name]=&columns[4][searchable]=true&columns[4][orderable]=false&columns[4][search][value]=&columns[4][search][regex]=false&columns[5][data]=total_box_div()&columns[5][name]=&columns[5][searchable]=true&columns[5][orderable]=false&columns[5][search][value]=&columns[5][search][regex]=false&columns[6][data]=luxurious_div()&columns[6][name]=&columns[6][searchable]=true&columns[6][orderable]=false&columns[6][search][value]=&columns[6][search][regex]=false&columns[7][data]=precious_div()&columns[7][name]=&columns[7][searchable]=true&columns[7][orderable]=false&columns[7][search][value]=&columns[7][search][regex]=false&columns[8][data]=exquisite_div()&columns[8][name]=&columns[8][searchable]=true&columns[8][orderable]=false&columns[8][search][value]=&columns[8][search][regex]=false&columns[9][data]=common_div()&columns[9][name]=&columns[9][searchable]=true&columns[9][orderable]=false&columns[9][search][value]=&columns[9][search][regex]=false&start=0&length=20&search[value]=&search[regex]=false&uid=${uid}&_=1684712560846`
        } else {
            url = `https://feixiaoqiu.com/search_achievement_ajax/?draw=1&columns[0][data]=total_index_div()&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=false&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=nick_name_div()&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=false&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=title_div()&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=false&columns[2][search][value]=&columns[2][search][regex]=false&columns[3][data]=grade_div()&columns[3][name]=&columns[3][searchable]=true&columns[3][orderable]=false&columns[3][search][value]=&columns[3][search][regex]=false&columns[4][data]=achievement_number_div()&columns[4][name]=&columns[4][searchable]=true&columns[4][orderable]=false&columns[4][search][value]=&columns[4][search][regex]=false&start=0&length=20&search[value]=&search[regex]=false&uid=${uid}&_=1774705299791`
        }
        let response
        try {
            response = await (await fetch(url)).json();
        } catch (error) {
            logger.error(`接口请求失败！ ${error}`);
            e.reply(`接口请求失败~\n尝试读取${uid}本地[ #角色 ]数据`);
            return await getData(e, uid)
        }
        let str = JSON.stringify(response)
        str = str.replace(/(\r|\n|\t|\s|\\n)/g, '')
            .match(/\[(.*?)]/)[1]
            .replace(/\\"/g, '"')
            .replace(/"nick.*?me":\d,/g, '')
        let data = str ? JSON.parse(str) : ''
        if (data) {
            data.title = unescape(data.title.replace(/\\u/g, '%u'))
            // 成就
            if (data.achievement_number) {
                data = await checkData(uid, data)
            }
            return await Ranking.renderData(e, uid, data)
        } else {
            e.reply(`uid: ${uid} 没有匹配的数据, 尝试读取本地[ #角色 ]数据~`)
            return await getData(e, uid)
        }
    }

    async groupRanking(e) {
        try {
            let mode = e.box ? 'chest' : 'achieve';
            let data = await Data.readJSON(`${e.group_id}.json`, 'data')
            if (!data[mode]) {
                return e.reply(`暂无排名, 群内使用[ #${e.box ? '宝箱' : '成就'}排行 ]再重试... `);
            }
            data = _(data[mode])
                .map((value, key) => ({ qq: key, ...value }))
                .orderBy(`${e.box ? 'total_box' : 'achievement_number'}`, 'desc')
                .value();

            const rankData = data.map((value, index) => ({ ...value, rank: index + 1 }));
            let tops = rankData.slice(0, 3);
            tops = tops.concat(Array(3 - tops.length).fill({ total_index: 999999, qq: 10000 }));

            let { achievement } = await Ranking.getAchievement();
            data = {
                tops,
                rankData,
                box: e.box,
                achievement,
                save_id: e.group_id
            }
            return await Render.render(e, 'tops/groupRank', data)
        } catch (err) {
            return e.reply(`获取群排名失败！\n${err}`);
        }
    }
}
